<template>
  <div class="wrapper">
    <el-dialog
      title="结算信息"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <div>使用时间:{{ formattedTime }}</div>
      <div>原价:{{ settleTableSumPrice }}元</div>
      <div>会员价:{{ settleTableSumPrice * 0.9 }}</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doSettle">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="请选择是否有会员"
      :visible.sync="memberDialog"
      width="30%"
      :before-close="memberDialogClose"
    >
      <el-radio v-model="memberRadio" label="无会员"></el-radio>
      <el-radio v-model="memberRadio" label="有会员"></el-radio>
      <el-form
        style="margin-top: 20px"
        v-if="memberRadio === '有会员'"
        :model="member"
        :rules="PhoneNumRules"
        ref="PhoneNumRulesRef"
        label-width="90px"
      >
        <el-form-item label="会员号码:" prop="PhoneNum">
          <el-input v-model="member.PhoneNum"></el-input></el-form-item
      ></el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="memberDialogClose">取 消</el-button>
        <el-button type="primary" @click="bookingTable()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 测试 -->

    <!-- 搜索与添加区域 -->
    <div class="header">
      <el-row>
        <el-col :span="3">
          <el-input
            size="small"
            v-model="searchName"
            placeholder="请输入查找的桌名"
          >
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-select
            size="small"
            v-model="selectTypeValue"
            placeholder="请选择球桌类型"
          >
            <el-option
              v-for="item in options"
              :key="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-select
            size="small"
            v-model="selectStateValue"
            placeholder="请选择球桌状态"
          >
            <el-option
              v-for="item in stateOptions"
              :key="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-button
            size="small"
            @click="search"
            icon="el-icon-search"
            type="primary"
            >查找</el-button
          >
        </el-col>
      </el-row>
    </div>
    <div class="itemBox">
      <div class="item" v-for="item in paginationList" :key="item.court_id">
        <el-card :body-style="{ padding: '0px' }">
          <div class="billiardsName">{{ item.courts_table }}</div>
          <img
            v-if="item.courts_type_id === 1"
            :src="ImgSrcType1"
            class="imgTypeBg"
          />
          <img
            v-if="item.courts_type_id === 2"
            :src="ImgSrcType2"
            class="imgTypeBg"
          />
          <div class="typeContent">
            <el-tag
              size="mini"
              class="pointer"
              v-if="item.courts_status_id === 0"
              @click="openmemberDialog(item)"
              >订台</el-tag
            >
            <el-tag
              size="mini"
              class="pointer"
              v-if="item.courts_status_id === 1"
              type="success"
              @click="readSettle(item)"
              >去结算</el-tag
            >
            <el-tag
              size="mini"
              class="cursorNone"
              v-if="item.courts_status_id === 2"
              type="danger"
              >维护中</el-tag
            >
          </div>
        </el-card>
      </div>
    </div>
    <div class="paginationBlock" style="margin-top: 0px; margin-left: 300px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[15]"
        :page-size="pageSize"
        layout="total,sizes, prev, pager, next,jumper"
        :total="billiardTableList.length"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectTypeValue: "所有",
      selectStateValue: "所有",
      options: ["所有", "中8台球", "斯诺克"],
      stateOptions: ["所有", "无人使用", "正在使用", "维护中"],
      imgSrc: "",
      billiardTableList: [], //台球桌集合
      paginationList: [], //分页后的数据
      currentPage: 1, //当前页码
      pageSize: 15, //每页的数据条数
      ImgSrcType1: require("@/assets/img/type-1.jpg"),
      ImgSrcType2: require("@/assets/img/type-2.jpg"),
      searchName: "",
      dialogVisible: false,
      settleTableSumPrice: 0,
      formattedTime: "",
      tableDoSettle: {},
      memberDialog: false,
      memberRadio: false,
      member: {
        PhoneNum: "",
      },
      PhoneNumRules: {
        PhoneNum: [
          { required: true, message: "请输入您的电话号码", trigger: "blur" },
          {
            validator: function (rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) == false) {
                callback(new Error("手机号格式错误"));
              } else {
                callback();
              }
            },
          },
        ],
      },
      sequenceNumber: 0,
    };
  },
  methods: {
    // 获取分页之后的数据
    getPageData() {
      let start = (this.currentPage - 1) * this.pageSize;
      let end = start + this.pageSize;
      this.paginationList = this.billiardTableList.slice(start, end);
    },
    // 获取全部数据
    getlivestockInfo() {
      let that = this;
      that.$axios
        .get("/getCourtsAll") //补上后台接口即可
        .then((res) => {
          // 请求成功
          // 在组件初始化时同步球桌状态（如果需要）
          that.billiardTableList = res.data;
          // 获取页面数据后立马调用下面函数
          that.getPageData();
          return;
        })
        .catch((error) => {
          // 请求失败
          console.log("请求失败");
          console.log(error);
        });
    },
    // 每页条数改变时触发 选择一页显示多少行
    handleSizeChange(val) {
      this.pageSize = val;
      this.getPageData();
    },
    // 当前页改变时触发 跳转其他页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getPageData();
    },
    // 查询
    search() {
      let that = this;
      let params = new URLSearchParams();
      params.append("searchName", this.searchName);
      params.append("selectTypeValue", this.selectTypeValue);
      params.append("selectStateValue", this.selectStateValue);
      that.$axios
        .post("/getCourtsByInfo", params) //补上后台接口即可
        .then((res) => {
          // 请求成功
          that.billiardTableList = res.data;
          // 获取页面数据后立马调用下面函数
          that.getPageData();
          return;
        })
        .catch((error) => {
          // 请求失败
          console.log("请求失败");
          console.log(error);
        });
    },
    // 获取当前时间戳精确到秒或毫秒
    getCurrentTimestamp() {
      return Math.floor(Date.now() / 1000 /* for seconds */); // 如果要精确到毫秒则去掉除法和1000
    },
    // 定义格式化时间戳为日期字符串的方法
    formatTimestamp(timestamp) {
      const date = new Date(timestamp * 1000); // 如果timestamp已经是毫秒级别，则不需要乘以1000
      const year = date.getFullYear();
      const month = ("0" + (date.getMonth() + 1)).slice(-2);
      const day = ("0" + date.getDate()).slice(-2);
      const hours = ("0" + date.getHours()).slice(-2);
      return `1620${year}${month}${day}${hours}`;
    },
    // 生成订单ID
    generateOrderNo() {
      // 获取当前时间戳并格式化
      const timestampStr = this.formatTimestamp(this.getCurrentTimestamp());
      // 确保并发环境下的序列号原子性增长（这里简单加锁，实际应用中可能需要更复杂的同步机制）
      let currentSeq;
      if (typeof window !== "undefined" && window.localStorage) {
        currentSeq = parseInt(localStorage.getItem("orderSequence")) || 0;
        localStorage.setItem("orderSequence", String(currentSeq + 1));
      } else {
        // 如果没有本地存储，或者不是浏览器环境，此处应使用服务器端逻辑或合适的客户端状态管理库
        currentSeq = this.sequenceNumber++;
      }
      // 将时间戳与序列号拼接成订单号
      const orderNo = `${timestampStr.padStart(14, "0")}${currentSeq
        .toString()
        .padStart(3, "0")}`;
      return orderNo;
    },
    openmemberDialog(item) {
      this.tableDoSettle = item;
      this.memberDialog = true;
    },
    // 订台
    bookingTable() {
      if (this.memberRadio === "有会员") {
        this.determineMember();
      } else {
        this.doBookingTable();
      }
    },
    async doBookingTable() {
      let that = this;
      await that.$axios
        .get(
          `/doBookingTable?courts_status_id=${this.tableDoSettle.courts_status_id}&courts_table=${this.tableDoSettle.courts_table}`
        ) //补上后台接口即可打
        .then((res) => {
          console.log(res.data.trim());
          // 订台成功
          if (res.data.trim() == "订台成功") {
            that.$message({
              message: "订台成功",
              type: "success",
            });
          }
          // 获取页面数据后立马调用下面函数
          that.getlivestockInfo();
          that.getPageData();
          that.addorder();
        })
        .catch((error) => {
          // 请求失败
          console.log("请求失败");
          console.log(error);
        });
    },
    //判断该号码是否为会员
    determineMember() {
      let that = this;
      that.$axios
        .get(`/searchMemberByPhone?member_phone=${this.member.PhoneNum}`) //补上后台接口即可打
        .then((res) => {
          that.memberDialog = false;
          // 请求成功
          if (res.data === null) {
            that.$message({
              message: "此号码不是会员,请先注册",
              type: "warning",
            });
            return;
          } else {
            console.log(res.data.result);
            //判断该会员是否被禁用
            if (res.data.result != undefined) {
              that.$message({
                message: "该会员已被禁用,请联系店长",
                type: "warning",
              });
              return;
            }
            that.doBookingTable();
          }
        })
        .catch((error) => {
          // 请求失败
          console.log("请求失败");
          console.log(error);
        });
    },
    // 添加订单
    addorder() {
      let that = this;
      let params = new URLSearchParams();
      params.append("court_id", this.tableDoSettle.court_id);
      params.append("UUID", this.generateOrderNo());
      params.append("PhoneNum", this.member.PhoneNum);
      that.$axios
        .post("/addOrders", params)
        .then(() => {
          // 请求成功
          // console.log(res.data);
          return;
        })
        .catch((error) => {
          // 请求失败
          console.log("请求失败");
          console.log(error);
        });
    },
    // 准备结算
    readSettle(tableToUpdate) {
      this.tableDoSettle = tableToUpdate;
      let that = this;
      that.$axios
        .get(
          `/readSettle?courts_status_id=${tableToUpdate.courts_status_id}&courts_table=${tableToUpdate.courts_table}&court_id=${tableToUpdate.court_id}`
        ) //补上后台接口即可打
        .then((res) => {
          // 请求成功
          that.convertToHalfHours(res.data);
          return;
        })
        .catch((error) => {
          // 请求失败
          console.log("请求失败");
          console.log(error);
        });
    },
    // 转换时间格式
    formatMinutesToHoursAndMinutes(minutes) {
      let hours = Math.floor(minutes / 60);
      let remainingMinutes = minutes % 60;
      // 格式化输出小时和分钟
      this.formattedTime =
        hours +
        "小时" +
        (remainingMinutes < 10 ? "0" : "") +
        remainingMinutes +
        "分钟";
    },
    // 将后端传的时间进行判断
    convertToHalfHours(minutes) {
      minutes = 60;
      if (minutes < 15) {
        this.$message({
          message: "最少需要打到15分钟",
          type: "warning",
        });
        this.settleTableSumPrice = 0; // 少于15分钟不计费
        return;
      } else {
        this.dialogVisible = true;
        let halfHours = Math.ceil((minutes - 14) / 30); // 减去14分钟以确保从第15分钟开始计算
        if (this.tableDoSettle.courts_type_id === 2) {
          this.settleTableSumPrice = halfHours * 30;
        } else {
          this.settleTableSumPrice = halfHours * 15;
        }
        this.formatMinutesToHoursAndMinutes(halfHours * 30);
      }
    },
    // 去结算
    async doSettle() {
      let memberId = await this.isMemberByCourt_id(this.tableDoSettle.court_id);
      let that = this;
      let params = new URLSearchParams();
      if (memberId !== "1") {
        params.append("total_amount", this.settleTableSumPrice * 0.8);
        params.append("memberId", memberId);
      } else {
        params.append("total_amount", this.settleTableSumPrice);
      }
      params.append("court_id", this.tableDoSettle.court_id);
      that.$axios
        .post("/doSettle", params)
        .then((res) => {
          let resData = res.data;
          this.$message({
            message: resData.msg,
            type: resData.msgType,
          });
          // 请求成功
          that.dialogVisible = false;
          that.getlivestockInfo();
          that.getPageData();
          return;
        })
        .catch((error) => {
          // 请求失败
          console.log("请求失败");
          console.log(error);
        });
    },
    // 查找该球桌是否是会员在打
    isMemberByCourt_id(court_id) {
      let that = this;
      return that.$axios
        .get(`/isMemberByCourt_id?court_id=${court_id}`)
        .then((res) => {
          // 请求成功
          return res.data;
        })
        .catch((error) => {
          // 请求失败
          console.log("请求失败");
          console.log(error);
        });
    },
    handleClose() {
      this.dialogVisible = false;
    },
    memberDialogClose() {
      this.memberDialog = false;
    },
    parseAndFormatDateString(dateStr) {
      // 解析美国英语格式的日期字符串
      const dateParts = dateStr.split(/[\s,]+/);
      const monthName = [
        "Jan",
        "Feb",
        "Mar",
        "Apr",
        "May",
        "Jun",
        "Jul",
        "Aug",
        "Sep",
        "Oct",
        "Nov",
        "Dec",
      ];
      const monthIndex = monthName.indexOf(dateParts[0]);

      // 创建Date对象
      const date = new Date(
        dateParts[2],
        monthIndex,
        parseInt(dateParts[1]),
        dateParts[3].toLowerCase().endsWith("pm")
          ? parseInt(dateParts[3].split(":")[0]) + 12
          : parseInt(dateParts[3].split(":")[0]),
        parseInt(dateParts[3].split(":")[1]),
        parseInt(dateParts[3].split(":")[2])
      );

      // 格式化为"YYYY-MM-DD HH:mm:ss"
      let year = date.getFullYear();
      let month = ("0" + (date.getMonth() + 1)).slice(-2);
      let day = ("0" + date.getDate()).slice(-2);
      let hours = ("0" + date.getHours()).slice(-2);
      let minutes = ("0" + date.getMinutes()).slice(-2);
      let seconds = ("0" + date.getSeconds()).slice(-2);

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
  },
  mounted() {
    this.getlivestockInfo();
  },
};
</script>

<style scoped>
.wrapper .itemBox {
  margin: 10px;
  display: inline-grid;
  grid-template-columns: repeat(5, 222px);
  grid-gap: 13px;
  grid-template-rows: 185px * 3;
}

.wrapper > .itemBox > .item {
  text-align: center;
  font-size: 200%;
  color: #fff;
}

.imgTypeBg {
  opacity: 0.9;
  width: 100%;
  height: 160px;
  margin-bottom: -5px;
}

.billiardsName {
  padding: 2px;
  font-size: 15px;
}

.typeContent {
  display: flex;
  flex-direction: row;
  justify-content: space-evenly;
  align-items: center;
  height: 25px;
}

.pointer {
  cursor: pointer;
}

.cursorNone {
  cursor: none;
}

.header {
  padding-left: 10px;
}

.header > .el-row > .el-col {
  margin-right: 10px;
}
</style>
